import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Select, Radio, InputNumber, Upload, Image, message, Switch, Tabs } from 'antd';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { createCourse, updateCourse, getCategoryList } from '@/services/courseManagementApi';
import { uploadImage } from '@/services/systemManagementApi';

interface CourseFormProps {
  visible: boolean;
  mode: 'create' | 'edit';
  initialValues?: COURSE.CourseModel;
  onCancel: () => void;
  onSuccess: () => void;
}

const CourseForm: React.FC<CourseFormProps> = ({
  visible,
  mode,
  initialValues,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [coverImageUrl, setCoverImageUrl] = useState<string>('');
  const [categories, setCategories] = useState<COURSE.CategoryModel[]>([]);
  const [activeTab, setActiveTab] = useState('basic');

  useEffect(() => {
    if (visible) {
      loadCategories();
      if (mode === 'edit' && initialValues) {
        form.setFieldsValue(initialValues);
        setCoverImageUrl(initialValues.cover || '');
      } else {
        form.resetFields();
        setCoverImageUrl('');
      }
    }
  }, [visible, mode, initialValues, form]);

  // 加载分类列表
  const loadCategories = async () => {
    try {
      const response = await getCategoryList({ page: 1, limit: 100 });
      setCategories(response.data.list);
    } catch (error) {
      console.error('加载分类失败:', error);
    }
  };

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const submitData = {
        ...values,
        cover: coverImageUrl,
      };

      if (mode === 'create') {
        await createCourse(submitData);
        message.success('课程创建成功');
      } else {
        await updateCourse(initialValues!.id, submitData);
        message.success('课程更新成功');
      }

      onSuccess();
    } catch (error) {
      message.error(mode === 'create' ? '课程创建失败' : '课程更新失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理封面上传
  const handleCoverUpload = async (file: File) => {
    try {
      const response = await uploadImage(file);
      setCoverImageUrl(response.data.url);
      message.success('封面上传成功');
      return false;
    } catch (error) {
      message.error('封面上传失败');
      return false;
    }
  };

  const tabItems = [
    {
      key: 'basic',
      label: '基本信息',
      children: (
        <>
          <Form.Item
            name="title"
            label="课程标题"
            rules={[
              { required: true, message: '请输入课程标题' },
              { max: 100, message: '标题不能超过100个字符' },
            ]}
          >
            <Input placeholder="请输入课程标题" />
          </Form.Item>

          <Form.Item
            name="subtitle"
            label="副标题"
            rules={[{ max: 200, message: '副标题不能超过200个字符' }]}
          >
            <Input placeholder="请输入课程副标题" />
          </Form.Item>

          <Form.Item label="封面图片">
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              {coverImageUrl && (
                <Image
                  src={coverImageUrl}
                  alt="课程封面"
                  width={120}
                  height={80}
                  style={{ objectFit: 'cover', borderRadius: 4 }}
                />
              )}
              <Upload
                showUploadList={false}
                beforeUpload={handleCoverUpload}
                accept="image/*"
              >
                <div style={{
                  width: 120,
                  height: 80,
                  border: '1px dashed #d9d9d9',
                  borderRadius: 4,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  cursor: 'pointer',
                }}>
                  <div style={{ textAlign: 'center' }}>
                    <PlusOutlined />
                    <div style={{ marginTop: 8, fontSize: '12px' }}>上传封面</div>
                  </div>
                </div>
              </Upload>
            </div>
          </Form.Item>

          <Form.Item
            name="category_id"
            label="课程分类"
            rules={[{ required: true, message: '请选择课程分类' }]}
          >
            <Select placeholder="请选择课程分类">
              {categories.map(category => (
                <Select.Option key={category.id} value={category.id}>
                  {category.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="difficulty"
            label="难度等级"
            rules={[{ required: true, message: '请选择难度等级' }]}
          >
            <Radio.Group>
              <Radio value="beginner">初级</Radio>
              <Radio value="intermediate">中级</Radio>
              <Radio value="advanced">高级</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Select.Option value="draft">草稿</Select.Option>
              <Select.Option value="published">已发布</Select.Option>
              <Select.Option value="archived">已归档</Select.Option>
            </Select>
          </Form.Item>
        </>
      ),
    },
    {
      key: 'content',
      label: '内容描述',
      children: (
        <>
          <Form.Item
            name="description"
            label="课程简介"
            rules={[
              { required: true, message: '请输入课程简介' },
              { max: 500, message: '简介不能超过500个字符' },
            ]}
          >
            <Input.TextArea
              rows={4}
              placeholder="请输入课程简介"
              showCount
              maxLength={500}
            />
          </Form.Item>

          <Form.Item
            name="content"
            label="课程详情"
            rules={[{ required: true, message: '请输入课程详情' }]}
          >
            <Input.TextArea
              rows={6}
              placeholder="请输入课程详情"
            />
          </Form.Item>

          <Form.Item
            name="objectives"
            label="学习目标"
          >
            <Input.TextArea
              rows={3}
              placeholder="请输入学习目标，每行一个"
            />
          </Form.Item>

          <Form.Item
            name="prerequisites"
            label="前置要求"
          >
            <Input.TextArea
              rows={3}
              placeholder="请输入前置要求"
            />
          </Form.Item>
        </>
      ),
    },
    {
      key: 'settings',
      label: '课程设置',
      children: (
        <>
          <Form.Item
            name="price"
            label="课程价格"
            rules={[
              { required: true, message: '请输入课程价格' },
              { type: 'number', min: 0, message: '价格不能为负数' },
            ]}
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入课程价格，0表示免费"
              min={0}
              precision={2}
              addonAfter="元"
            />
          </Form.Item>

          <Form.Item
            name="duration"
            label="课程时长"
            rules={[
              { type: 'number', min: 1, message: '课程时长至少为1分钟' },
            ]}
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入课程时长"
              min={1}
              addonAfter="分钟"
            />
          </Form.Item>

          <Form.Item
            name="max_students"
            label="最大学员数"
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入最大学员数，0表示不限制"
              min={0}
            />
          </Form.Item>

          <Form.Item
            name="is_featured"
            label="是否推荐"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="allow_preview"
            label="允许试看"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="certificate_enabled"
            label="完成证书"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="tags"
            label="课程标签"
          >
            <Select
              mode="tags"
              placeholder="请输入课程标签"
              style={{ width: '100%' }}
            />
          </Form.Item>
        </>
      ),
    },
  ];

  return (
    <Modal
      title={mode === 'create' ? '新建课程' : '编辑课程'}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      width={800}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          difficulty: 'beginner',
          status: 'draft',
          price: 0,
          is_featured: false,
          allow_preview: true,
          certificate_enabled: false,
        }}
      >
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={tabItems}
        />
      </Form>
    </Modal>
  );
};

export default CourseForm;
